#! /user/bin/python3
# coding-utf-8
# @Time = 2025/4/17 10:39
# @Author:Poolaris
import requests
from common.yaml_config import GetConf
from common.tools import get_every_wallpaper
from common.process_redis import Process


def send_qywx_talk_msg(webhook, content):
    """
    发送机器人消息-text
    :param webhook:
    :param content:
    :return:
    """
    headers = {"Content-Type": "application/json ;charset=utf-8"}
    data = {
        "msgtype": "text",
        "text": {"content": content}
    }
    res = requests.post(url=webhook, json=data, headers=headers)
    print("发送机器人消息，返回结果：", res.text)


def send_qywx_msg_markdown(
        qywx_webhook,
        allure_url,
        report_title,
        total_count,
        success_count,
        fail_count,
        failed_testcases_name,
):
    """
    发送markdown格式消息到企业微信
    :param qywx_webhook:机器人
    :param allure_url:allure地址
    :param total_count:测试用例总数
    :param success_count:成功数
    :param fail_count:失败数
    :param failed_testcases_name:失败用例名称
    :param report_title:报告标题
    :return:
    """
    # 获取壁纸
    # wallpaper_url = get_every_wallpaper()
    # headers = {"Content-Type": "application/json ;charset=utf-8"}
    if fail_count == 0:
        failed_testcases_name = ""
    data = {
        "msgtype": "markdown",
        "markdown": {
            "content": "#### "
                       + report_title
                       + " \n >用例总数：{}个 \n > 测试结果：\n> 通过{}个 , 失败{}个{} \n>   ###### 点击查看测试报告 \n>  [Allure测试报告]({})".format(
                total_count,
                success_count,
                fail_count,
                failed_testcases_name,
                allure_url,
            ),
        },
    }
    res = requests.post(url=qywx_webhook, json=data)
    print(res.text)
    return True


if __name__ == '__main__':
    webhook = GetConf().get_qywx_webhook()
    total, success, fail, _ = Process().get_result()
    # 插入测试结束时间
    Process().write_end_time()
    # 更改运行状态为0
    Process().modify_running_status(0)

    # 项目名称
    project_name = "trading_test"

    # 报告名称
    report_title = "UI自动化测试报告"

    # jenkins地址
    jenkins_url = GetConf().get_jenkins()["url"]

    # 测试报告地址
    allure_url = jenkins_url + "/job/" + project_name + "/allure/"
    failed_testcases_name = ",失败的用例为: "
    send_qywx_talk_msg(webhook, "测试消息")
    send_qywx_msg_markdown(
        webhook,
        allure_url,
        report_title,
        total,
        success,
        fail,
        failed_testcases_name
    )
